//
//  LendPandectViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/5.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "LendPandectViewController.h"
#import "MineViewController.h"
#import "MXNCircleCharts.h"
#import "LendPandectTableViewCell.h"
#import "InterestDetailViewController.h"
#import "LendContractViewController.h"
#define backButtonW 24/WIDTH_6_SCALE
#define backButtonH 30/WIDTH_6_SCALE
@interface LendPandectViewController ()<UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UILabel * naviTitle;//navigationItem
@property (nonatomic, strong)MXNCircleCharts *circle;//圆环
@property (nonatomic, strong)UILabel * profitContentLab;//收益
@property (nonatomic, strong)UILabel * principalContentLab;//本金
@property (nonatomic, strong)UILabel * sectionTitleLab;
@property (nonatomic, strong)NSMutableArray * cellArr;
@property (nonatomic, strong)NSString * earnings;//预期收益总额
@property (nonatomic, strong)NSString * haveEarnedmoney;//已赚取收益总额
@property (nonatomic, strong)NSString * productPrice;//投资本金总额
- (void)makeUpCircleParameter;//圆环参数
@end

@implementation LendPandectViewController(networking)
//所持有的标的
- (void)holdingBidData{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"phone":[UserModel sharedInstanced].mobile,
                           @"token":[UserModel sharedInstanced].token,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"phone":[UserModel sharedInstanced].mobile,
                               @"token":[UserModel sharedInstanced].token,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/order/index?api=api1001"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSString * compareMD5Str = [md5Code encodeStringWithDictionary:dictionary];
            NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    if ([compareMD5Str isEqualToString:signResult]) {
                        NSLog(@"成功");
                        [self.cellArr removeAllObjects];
                        [self.cellArr addObjectsFromArray:jsonData[@"body"]];
                        [self.tableView reloadData];
                    }else{
                        ShowMessage(jsonData[@"msg"]);
                    }
                }else{
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }

            
            
        }
    }];
}
//持有中投资接口
- (void)holdingMoneyData{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"phone":[UserModel sharedInstanced].mobile,
                           @"token":[UserModel sharedInstanced].token,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"phone":[UserModel sharedInstanced].mobile,
                               @"token":[UserModel sharedInstanced].token,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/order/index?api=api1008"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSString * compareMD5Str = [md5Code encodeStringWithDictionary:dictionary];
            NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    if ([compareMD5Str isEqualToString:signResult]) {
                        NSLog(@"成功");
                        self.earnings = [jsonData[@"body"][0] objectForKey:@"earnings"];//红色数据
                        self.haveEarnedmoney = [jsonData[@"body"][0] objectForKey:@"havebeen_money"];//圆环标题
                        self.productPrice = [jsonData[@"body"][0] objectForKey:@"productPrice"];//蓝色数据
                        
                        [self makeUpCircleParameter];//圆环参数
                        [self.tableView reloadData];
                    }else{
                        NSLog(@"失败");
                        ShowMessage(jsonData[@"msg"]);
                    }
                }else{
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }

            
            
        }
    }];
}
@end
@implementation LendPandectViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
    
    [self holdingBidData];//所持有的标的
    [self holdingMoneyData];//持有中投资接口
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.delegate = self;
    self.navigationItem.title = @"持有中出借总览";
    self.view.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
}
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
    BOOL isHomePage = [viewController isKindOfClass:[self class]];
    BOOL isMinePage = [viewController isKindOfClass:[MineViewController class]];
    if (isHomePage) {
        [self.navigationController setNavigationBarHidden:isHomePage animated:YES];
    }
    if (isMinePage) {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
}
#pragma mark - init
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = self.headerView;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[LendPandectTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LendPandectTableViewCell class])];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] init];
        UIButton * backBtn = [[UIButton alloc] init];
        [backBtn setImage:[UIImage imageNamed:@"out"] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:backBtn];
        if (Is_Iphone_X) {
            _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 360/WIDTH_6_SCALE + 24);
            backBtn.frame = CGRectMake(18/WIDTH_6_SCALE, 14/WIDTH_6_SCALE + 24 + 20, backButtonW, backButtonH);
        }else{
            _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 360/WIDTH_6_SCALE);
            backBtn.frame = CGRectMake(18/WIDTH_6_SCALE, 14/WIDTH_6_SCALE + 20, backButtonW, backButtonH);
        }
        _headerView.backgroundColor = [UIColor whiteColor];
        //navigationItem
        self.naviTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150/WIDTH_6_SCALE, 15/WIDTH_6_SCALE)];
        self.naviTitle.centerX = self.view.centerX;
        self.naviTitle.centerY = backBtn.centerY;
        [self label:self.naviTitle withFont:DEF_FontSize_14 withText:@"持有中出借总览" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentCenter withView:_headerView];
        //圆环
        [self setupCircle];
        
        int borderW = (217 - 187.5)/WIDTH_6_SCALE;
        //收益红框
        UIImageView * redFrameView = [[UIImageView alloc] initWithFrame:CGRectMake(70/WIDTH_6_SCALE, self.circle.bottom + 22/WIDTH_6_SCALE, 8/WIDTH_6_SCALE, 8/WIDTH_6_SCALE)];
        redFrameView.backgroundColor = [UIColor redColor];
        [_headerView addSubview:redFrameView];
        //收益标题
        UILabel * profitTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(redFrameView.right + 10/WIDTH_6_SCALE, 0, 100/WIDTH_6_SCALE, 10/WIDTH_6_SCALE)];
        profitTitleLab.centerY = redFrameView.centerY;
        [self label:profitTitleLab withFont:DEF_FontSize_10 withText:@"预期收益总额" withTextColor:getColor(@"767676") withTextAlignment:NSTextAlignmentLeft withView:_headerView];
        //收益数额中心
        int profitContentLabCenterX = (profitTitleLab.right - redFrameView.left)/2 + redFrameView.left;
        //本金蓝框
        UIImageView * blueFrameView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2 + borderW , redFrameView.top, redFrameView.width, redFrameView.height)];
        blueFrameView.backgroundColor = getColor(@"3675bd");
        [_headerView addSubview:blueFrameView];
        //本金标题
        UILabel * principalTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(blueFrameView.right + 10/WIDTH_6_SCALE, profitTitleLab.top, profitTitleLab.width, profitTitleLab.height)];
        [self label:principalTitleLab withFont:DEF_FontSize_10 withText:@"持有中出借本金" withTextColor:getColor(@"767676") withTextAlignment:NSTextAlignmentLeft withView:_headerView];
        //收益内容
        self.profitContentLab = [[UILabel alloc] initWithFrame:CGRectMake(0, profitTitleLab.bottom + 7/WIDTH_6_SCALE, SCREEN_WIDTH/2 - redFrameView.left + 15/WIDTH_6_SCALE, 17/WIDTH_6_SCALE)];
        self.profitContentLab.centerX = profitContentLabCenterX;
        [self label:self.profitContentLab withFont:DEF_FontSize_18 withText:@"0" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:_headerView];
        //本金内容
        int principalContentLabX = blueFrameView.left + 3/WIDTH_6_SCALE;
        self.principalContentLab = [[UILabel alloc] initWithFrame:CGRectMake(principalContentLabX, self.profitContentLab.top, SCREEN_WIDTH - principalContentLabX, self.profitContentLab.height)];
        [self label:self.principalContentLab withFont:DEF_FontSize_18 withText:@"0" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:_headerView];
    }return _headerView;
}
- (NSMutableArray *)cellArr{
    if (!_cellArr) {
        _cellArr = @[].mutableCopy;
    }return _cellArr;
}
//圆环
- (void)setupCircle {
    CGFloat circleWidth = self.view.frame.size.width;
    CGFloat chartWidth = 210/WIDTH_6_SCALE;
    CGFloat circleX = (circleWidth - chartWidth) / 2;
    
//    self.circle = [[MXNCircleCharts alloc] initWithFrame:CGRectMake(circleX, self.naviTitle.bottom + 24/WIDTH_6_SCALE, chartWidth, chartWidth) withMaxValue:181063.73 value:180000];
    self.circle = [[MXNCircleCharts alloc] initWithFrame:CGRectMake(circleX, self.naviTitle.bottom + 24/WIDTH_6_SCALE, chartWidth, chartWidth) withMaxValue:0 value:0];
    [_headerView addSubview:self.circle];
}
//圆环参数
- (void)makeUpCircleParameter{
    float haveEarnedmoneyF = [self.haveEarnedmoney floatValue];
    float productPriceF = [self.productPrice floatValue];
    [self.circle rebuildCircleWithMaxValue:haveEarnedmoneyF value:productPriceF];
    self.circle.centerX = SCREEN_WIDTH/2;
    self.circle.valueTitle = @"预期回款总额(元)";
    self.circle.valueColor = getColor(@"737373");
    self.circle.insideCircleColor = getColor(@"ff4433");
    self.circle.title = self.haveEarnedmoney;
    self.circle.titleColor = [UIColor blackColor];
    self.circle.colorArray = @[getColor(@"3675bd"), getColor(@"3675bd")];
    self.circle.locations = @[@0.15,@0.85];
    self.profitContentLab.text = self.earnings;//红色
    self.principalContentLab.text = self.productPrice;//蓝色
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LendPandectTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LendPandectTableViewCell class]) forIndexPath:indexPath];
    cell.model = self.cellArr[indexPath.row];
    cell.rateBtnBlock = ^(NSString * bidID) {
        InterestDetailViewController * interestDetailVC = [[InterestDetailViewController alloc] init];
        interestDetailVC.bidID = bidID;
        [self.navigationController pushViewController:interestDetailVC animated:YES];
    };
    cell.contractBtnBlock = ^(NSString * bidID){
        LendContractViewController * lendContractVC = [[LendContractViewController alloc] init];
        lendContractVC.bidID = bidID;
        [self.navigationController pushViewController:lendContractVC animated:YES];
    };
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellArr.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 111/WIDTH_6_SCALE;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64/WIDTH_6_SCALE)];
    sectionView.backgroundColor = [UIColor whiteColor];
    //间隔
    UIView * upTopLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
    upTopLineView.backgroundColor = getColor(grayColor);
    [sectionView addSubview:upTopLineView];
    UIView * grayView = [[UIView alloc] initWithFrame:CGRectMake(0, upTopLineView.bottom, SCREEN_WIDTH, 13/WIDTH_6_SCALE)];
    grayView.backgroundColor = getColor(grayBGColor);
    [sectionView addSubview:grayView];
    UIView * upBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, grayView.bottom, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
    upBottomLineView.backgroundColor = getColor(grayColor);
    [sectionView addSubview:upBottomLineView];
    //内容
    self.sectionTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, upBottomLineView.bottom + 22/WIDTH_6_SCALE, SCREEN_WIDTH - 36/WIDTH_6_SCALE, 13/WIDTH_6_SCALE)];
    //    self.sectionTitleLab.text = @"持有中出借 共2笔";
    self.sectionTitleLab.text = [NSString stringWithFormat:@"持有中出借 共%lu笔", (unsigned long)self.cellArr.count];
    self.sectionTitleLab.font = DEF_FontSize_12;
    [sectionView addSubview:self.sectionTitleLab];
    //分割线
    UIView * downLineView = [[UIView alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, sectionView.bottom - 1/WIDTH_6_SCALE, SCREEN_WIDTH - 36/WIDTH_6_SCALE, 1/WIDTH_6_SCALE)];
    downLineView.backgroundColor = getColor(borderColor);
    [sectionView addSubview:downLineView];
    return sectionView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 64/WIDTH_6_SCALE;
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
